import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpErrorResponse } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
import { ToasterService } from 'app/modules/share/services/toaster.service';
import { SettingsService } from 'app/modules/settings/services/settings.service';
import { EMPTY } from 'rxjs';
import { timeout } from 'rxjs/operators';

@Injectable({
  providedIn: 'root',
})
export class ApiErrorHandingInterceptor implements HttpInterceptor {
  licenseInfo$ = this.settingsService.licenseInfo$;
  constructor(private toaster: ToasterService, private settingsService: SettingsService) {}
  intercept=(function(){
    let canToast401=true;
    return function(req: HttpRequest<any>, next: HttpHandler) {
      if (req.url === '/api/admin/license') {
        return next.handle(req);
      }
      
      return next.handle(req).pipe(
        timeout(10000),
        catchError((err: HttpErrorResponse) => {
          if(err.status==401){
            if(!location.pathname.startsWith('/login') && !req.url.endsWith('islogin')&& !req.url.endsWith('logout')){
              let message=err.error.message||'登陆已过期，请重新登录'
              let msg=throwError(message);
  
              if(canToast401){
                canToast401=false;
                this.toaster.warn(message);
                // window['$angularToast'].t.error(message)
                
              }

              canToast401=false;
              setTimeout(()=>{
                  canToast401=true;
                  location.href=location.origin;
              },1000)


              return msg;

              // alert(err.error.message)
              // alert('hello')
              // console.log('fucku err--:',err);
            }
          }
          
          if (err.status === 400 || err.status === 403) {
            if (err.error.error) {
              this.toaster.warn(err.error.error);
              return throwError(err.error);
            }
            this.toaster.warn(err.error.message);
            return throwError(err.error);
          }
          if (err.error && typeof err.error === 'object') {
            if (err.error.code) {
              this.toaster.warn(err.error.error, err.error.code);
              return throwError(err.error);
            }
            if (err.error.error) {
              switch (true) {
                case new RegExp('^no .*id$').test(err.error.error):
                  this.toaster.warn('未选择');
                  break;
                default:
                  this.toaster.warn(err.error.error);
              }
              return throwError(err.error);
            }
          }
          if (err.status >= 500) {
            this.toaster.warn(err.message, '网络错误');
          }
          return throwError(err);
        }),
      );
    }
  })();
}
